package com.xxl.job.core.commons.exception;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.xxl.job.core.commons.response.ReturnCode;
import com.xxl.job.core.commons.response.ReturnT;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author xuyue
 * @email xuyue@cetcbigdata.com
 * @date 2021-4-21 8:53
 */
@Data
public class DataxException extends RuntimeException {
    private Logger logger = LoggerFactory.getLogger(DataxException.class);

    private static final long serialVersionUID = 1L;

    private String msg;
    private int code = 500;
    private String errorMsg;

    /**
     * description : 抛出异常
     */
    public static void cast(String msg, ReturnCode returnCode) {
        throw new DataxException(msg, returnCode.getCode());
    }

    /**
     * description : 抛出异常
     */
    public static void cast(ReturnT returnT) {
        if (null == returnT) {
            throw new DataxException(ReturnCode.ERROR.getMsg());
        }
        throw new DataxException(returnT.getCode(), returnT.getMsg());
    }


    /**
     * description : 抛出异常
     */
    public static void cast(ReturnCode returnCode) {
        throw new DataxException(returnCode.getMsg(), returnCode.getCode());
    }


    /**
     * description : 自定义异常
     */
    public DataxException(ReturnCode returnCode, String msg) {
        super(msg);
        this.msg = msg;
        this.code = returnCode.getCode();
    }

    /**
     * description : 自定义异常
     */
    public DataxException(ReturnCode returnCode, String msg, String errorMsg) {
        super(msg);
        this.msg = msg;
        this.code = returnCode.getCode();
        this.errorMsg = errorMsg;
    }

    public DataxException(String msg) {
        super(msg);
        this.msg = msg;
    }

    public DataxException(JSONObject result) {
        super(result.toJSONString());
        String msg = "";
        Integer code = 10000;
        try {
            msg = result.getString("msg");
            code = result.getInteger("code");
        } catch (JSONException e) {
            logger.error("获取code和msg异常：" + result.toJSONString());
        }
        this.msg = msg;
        this.code = code;
    }


    public DataxException(String msg, Throwable e) {
        super(msg, e);
        this.msg = msg;
    }

    public DataxException(String msg, int code) {
        super(msg);
        this.msg = msg;
        this.code = code;
    }

    public DataxException(Integer code, String msg) {
        super(msg);
        this.msg = msg;
        this.code = code;
    }

    public DataxException(String msg, int code, Throwable e) {
        super(msg, e);
        this.msg = msg;
        this.code = code;
    }

}
